import request from './request.js';
import {
  requestBaseUrl,
} from './common.js';


export const ajax = async (url = '', param = {}, config = {}) => {
  const baseUrl = requestBaseUrl;
  const configFormat = {
    method: config.method || 'post',
    data: param,
    baseUrl: `${baseUrl}/${url}`,
    ...config,
  };
  if (configFormat.method === 'get') {
    configFormat.params = configFormat.data;
  }
  return await request(configFormat);
};

export const ajaxAll = async (requestList) => {
  const resultList = [];
  return new Promise((resolve, reject) => {
    requestList.forEach((val, index) => {
      val.fn(val.param).then((res) => {
        resultList[ index ] = res;
        if (resultList.length === requestList.length) {
          resolve(requestList);
        }
      }).catch((e) => {
        resultList[ index ] = e;
        if (resultList.length === requestList.length) {
          resolve(requestList);
        }
      });
    });
  });
};


export default {
  ajax,
};
